package com.recipedb.sprint.repository;

import com.recipedb.sprint.entity.Rewards;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RewardsRepository extends JpaRepository<Rewards, Long> {

    /**
     * 查询库存大于0的奖品，并按积分需求升序
     */
    List<Rewards> findByStockGreaterThanOrderByPointsRequiredAsc(int stock);

    /**
     * 扣库存
     * 返回受影响行数，0表示扣库存失败（库存不足或id不存在）
     */
    @Modifying
    @Query("update Rewards r set r.stock = r.stock - ?2 where r.rewardId = ?1 and r.stock >= ?2")
    int reduceStock(Long rewardId, int quantity);
}
